package com.jstyle.jclifexd.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.jstyle.blesdk.Util.ResolveUtil;
import com.jstyle.blesdk.Util.SingleDealData;
import com.jstyle.blesdk.callback.DataListener;
import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.blesdk.model.DeviceBean;
import com.jstyle.blesdk.model.GetData;
import com.jstyle.blesdk.model.SetPersonalInfo;
import com.jstyle.blesdk.model.SetTime;
import com.jstyle.jclifexd.NetWork.NetWorkException;
import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.activity.FileUpdateActivity;
import com.jstyle.jclifexd.activity.GpsUpdateActivity;
import com.jstyle.jclifexd.activity.OtaActivity;
import com.jstyle.jclifexd.app.MyApplication;
import com.jstyle.jclifexd.ble.BleManager;
import com.jstyle.jclifexd.ble.BleService;
import com.jstyle.jclifexd.daoManager.StepDataDaoManager;
import com.jstyle.jclifexd.daoManager.UserInfoDaoManager;
import com.jstyle.jclifexd.model.BleData;
import com.jstyle.jclifexd.model.Device1810;
import com.jstyle.jclifexd.model.Device181003;
import com.jstyle.jclifexd.model.JstyleDevice;
import com.jstyle.jclifexd.model.NetResultData;
import com.jstyle.jclifexd.model.UpdateData;
import com.jstyle.jclifexd.model.UserInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

import static com.mob.tools.utils.Strings.getString;

public class BleSendSingleton implements DataListener {
    private static Context context;
    private boolean isSycData;
    private static final BleSendSingleton ourInstance = new BleSendSingleton();
    private static Disposable subscription;
    private static final String TAG = "BleSendSingleton";
    private int batteryValue;
    private AlertDialog gpsDialog;
    private long gpsFileLength;
    private String gpsFilePath;
    private int phoneDataLength;

    public static BleSendSingleton getInstance() {
        return ourInstance;
    }

    private BleSendSingleton() {
        subscribe();
    }

    /**
     * 设置设备时间;获取电量;获取设置的步数目标值;设置用户信息
     * 获取设备版本号1需要升级->下载升级文件开始升级；2不需要升级->检查资源文件是否需要升级
     * 资源文件需要升级-》升级然后重新连接;不需要升级-》获取设备时间检查是否需要升级gps
     * gps文件需要升级-》升级gps文件；不需要升级-》开始同步数据；
     */
    public void startSycData() {
        if (isSycData) return;
        isSycData = true;
        SetPersonalInfo setPersonalInfo = getDeviceUserInfo();
        offerData(SingleDealData.startGo());
        offerData(SingleDealData.setDeviceTime(new SetTime()));//设置设备时间以及时区
        offerData(SingleDealData.GetBatteryLevel());//获取电量（显示以及ota升级电量判断）
        offerData(SingleDealData.GetGoal());//获取设置的步数目标值
        if (setPersonalInfo != null) offerData(SingleDealData.setInfo(setPersonalInfo));//设置用户信息
        offerData(SingleDealData.getVersion());
        BleManager.getInstance().writeValue();
    }

    public void getDeviceTime() {
        BleManager.getInstance().writeValue(SingleDealData.getDeviceTime());
    }

    public void getStepData() {
        String date= StepDataDaoManager.getLastDataTime();
        BleManager.getInstance().writeValue(SingleDealData.getTotalDataWithDate(0,date));
    }

    private byte[]exerciseValue;
    public void getExerciseData() {
        if(!isSync())isSycData=true;
        BleManager.getInstance().writeValue(SingleDealData.GetSportDataWithDate(0, ""));
    }
    public boolean isSync() {
       return isSycData;
    }
    private void offerData(byte[] value) {
        BleManager.getInstance().offerValue(value);
    }

    public void clean() {
        isSycData = false;
    }

    protected void subscribe() {

        RxBus.getInstance().toObservable(BleData.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<BleData>() {
            @Override
            public void onSubscribe(Disposable d) {
                subscription = d;
            }

            @Override
            public void onNext(BleData bleData) {
                String action = bleData.getAction();
                if (action.equals(BleService.ACTION_DATA_AVAILABLE)) {
                    byte[] value = bleData.getValue();
                    SingleDealData.receiveUpdateValue(value, ourInstance);
                } else if (action.equals(BleService.ACTION_GATT_onDescriptorWrite)) {

                    // onConnect();
                } else if (action.equals(BleService.ACTION_GATT_DISCONNECTED)) {
                    //  onDisconnect();
                    clean();
                } else if (OtaActivity.Action_Dfu_Failed.equals(action)) {

                }


            }


            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void dataCallback(Map<String, String> maps, SendCmdState sendCmdState) {
        switch (sendCmdState) {
            case READ_VERSION:
                break;
            case CHECK_RESUPDATE:
                break;
            case GET_DEVICE_Time:
                break;
        }
    }

    @Override
    public void dataCallback(DeviceBean deviceBean, SendCmdState sendCmdState) {

    }

    private SetPersonalInfo getDeviceUserInfo() {
        String account = NetWorkUtil.getUserId();
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(account);
        if (userInfo == null) return null;
        SetPersonalInfo setPersonalInfo = new SetPersonalInfo();
        Calendar calendar = Calendar.getInstance();
        int nowYear = calendar.get(Calendar.YEAR);
        int userYear = Integer.parseInt(userInfo.getBirthday().split("-")[0]);
        float height = userInfo.getHeight();
        float weight = userInfo.getWeight();
        setPersonalInfo.setAge(nowYear - userYear);
        setPersonalInfo.setHeight((int) height);
        setPersonalInfo.setWeight((int) weight);
        setPersonalInfo.setSex(userInfo.getGender() == 0 ? 1 : 0);
        return setPersonalInfo;
    }


}
